package com.lp.test.processor;


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//Bean后置处理器实现类，两个方法在初始化之前和之后执行，可以通过实现类使用JDK的Proxy.newProxyInstance()；基于反射实现aop。
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {



    @Override
    public Object postProcessBeforeInitialization(Object bean,String beanName) {
        if ("userService".equals(beanName)) {
            System.out.println("BeanPostProcessor实现类的postProcessBeforeInitialization()方法");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean,String beanName) {
        if ("userService".equals(beanName)) {
            //代理对象，通过JDK的Proxy.newProxyInstance()；基于反射实现aop。
            // 第一个参数类加载器，第二个参数接口的class对象，第三个参数重写invoke()的InvocationHandler实现类
            Object proxyInstance = Proxy.newProxyInstance(MyBeanPostProcessor.class.getClassLoader(),
                    bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("切面逻辑，BeanPostProcessor实现类的postProcessAfterInitialization()方法");
                    return method.invoke(bean,args);
                }
            });
            return proxyInstance;
        }
        return bean;
    }
}
